package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/7 10:01
 * https://leetcode-cn.com/problems/backspace-string-compare/
 */
public class Title844 {

    public static boolean backspaceCompare(String s, String t) {
        int flagS = 0, flagT = 0;
        int i = s.length() - 1;
        int j = t.length() - 1;
        while (i >= 0 || j >= 0) {
            //找到去除#号的第一个字母
            while (i >= 0) {
                if (s.charAt(i) == '#') {
                    flagS++;
                    i--;
                } else if (flagS > 0) {
                    flagS--;
                    i--;
                } else {
                    break;
                }
            }
            while (j >= 0) {
                if (t.charAt(j) == '#') {
                    flagT++;
                    j--;
                } else if (flagT > 0) {
                    flagT--;
                    j--;
                } else {
                    break;
                }
            }
            if (i >= 0 && j >= 0) {
                if (s.charAt(i) != s.charAt(j)) {
                    return false;
                }
            } else {
                if (i >= 0 || j >= 0) {
                    return false;
                }
            }
            i--;
            j--;
        }
        return true;
    }











    public static boolean backspaceCompare1(String s, String t) {
        int i = s.length() - 1;
        int j = t.length() - 1;
        int countA = 0, countB = 0;
        while (i >= 0 || j >= 0) {
            while (i >= 0) {
                if (s.charAt(i) == '#') {
                    i--;
                    countA++;
                } else if (countA > 0) {
                    countA--;
                    i--;
                } else {
                    //countA==0
                    break;
                }
            }
            while (j >= 0) {
                if (t.charAt(j) == '#') {
                    j--;
                    countB++;
                } else if (countB > 0) {
                    countB--;
                    j--;
                } else {
                    break;
                }
            }
            if (i >= 0 && j >= 0) {
                if (s.charAt(i) != t.charAt(j)) {
                    return false;
                }
            } else if (i >= 0 || j >= 0) {
                return false;
            }
            i--;
            j--;
        }
        return true;
    }

    public static void main(String[] args) {
        backspaceCompare("xywrrmp","xywrrmu#p");
    }
}
